package com.health.db.service.sm.impl;

import io.rong.RongCloud;
import io.rong.messages.TxtMessage;
import io.rong.models.CodeSuccessReslut;
import io.rong.models.PushMessage;
import io.rong.models.TokenReslut;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.health.commons.PropertiesService;
import com.health.commons.rongyun.AppTxtMsgMessage;
import com.health.commons.rongyun.CloseOrdMsgMessage;
import com.health.commons.rongyun.OrdMsgMessage;
import com.health.db.dao.user.IStuffListDao;
import com.health.db.dto.DoctorListDto;
import com.health.db.dto.StuffDetailDto;
import com.health.db.model.GoodsDataUser;
import com.health.db.model.RegisterOrder;
import com.health.db.model.StuffListExample;
import com.health.db.service.sm.IRongService;
import com.health.mapp.service.SpringContextUtil;
import com.health.mapp.utils.Constant;
import com.wxtools.api.IService;
import com.wxtools.bean.TemplateSender;
import com.wxtools.bean.result.TemplateSenderResult;

public class RongServiceImpl implements IRongService{
	
	private static Logger logger = Logger.getLogger(RongServiceImpl.class);
	private static String appKey=PropertiesService.getString("rong.appKey");
	private static String appSecret=PropertiesService.getString("rong.appSecret");
	IStuffListDao stuffListDao ;
	private IService mpService;
	
	@Override
	public TokenReslut getUserToken(String userId, String name,
			String portraitUri) {
		// TODO Auto-generated method stub
		TokenReslut tokenReslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		
			try {
				tokenReslut=rongCloud.user.getToken(userId, name, portraitUri);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
		return tokenReslut;
	}

	/**
	 * 刷新融云个人信息
	 * */
	@Override
	public CodeSuccessReslut refreshUserInfo(String userId, String userName,
			String portraitUri) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			reslut=rongCloud.user.refresh(userId, userName, portraitUri);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
			try {
				
				RongCloud rongCloud2 = RongCloud.getInstance(appKey, appSecret);
				reslut=rongCloud2.user.refresh(userId, userName, portraitUri);
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
			
				try {
					RongCloud rongCloud3 = RongCloud.getInstance(appKey, appSecret);
					reslut=rongCloud3.user.refresh(userId, userName, portraitUri);
					
				} catch (Exception e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
			}
		}
		return reslut;
	}

	/**
	 * 创建群组
	 * */
	@Override
	public CodeSuccessReslut createGroup(String[] userIds, String groupId,
			String groupName) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			reslut=rongCloud.group.create(userIds, groupId, groupName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(JSONArray.toJSONString(userIds));
			logger.error("userId="+JSONArray.toJSONString(userIds)+"-groupId="+groupId);
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	/**
	 * 加入群组
	 * */
	@Override
	public CodeSuccessReslut joinGroup(String[] userIds, String groupId,
			String groupName) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			rongCloud.group.join(userIds, groupId, groupName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("userId="+JSONArray.toJSONString(userIds)+"-groupId="+groupId);
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	

	/**
	 * 解散群组
	 * */
	@Override
	public CodeSuccessReslut dismissGroup(String userId, String groupId) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			rongCloud.group.dismiss(userId, groupId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("userId="+userId+"-groupId="+groupId);
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	/**
	 * 自定义消息，订单关闭
	 */
	@Override
	public CodeSuccessReslut PublishSystemCloseOrderMsg(String orderId, String userId,String[] toUserId) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			
			CloseOrdMsgMessage message = new CloseOrdMsgMessage(null , null,orderId);
			reslut = rongCloud.message.PublishSystem
			(userId, toUserId, message, 
					null, message.toString(), 0, 0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("toUserId="+JSONArray.toJSONString(toUserId)+"-groupId="+orderId+"-userId="+userId);
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	@Override
	public CodeSuccessReslut PublishSystemOrderToDocMsg(RegisterOrder order) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		mpService = (IService) SpringContextUtil.getBean("mpService");
	    TemplateSender  sender = packageTemplate(order);
		try {
			String[] toUserId=null;
			
			String channel = order.getRegisterguideid();
			if (Constant.CONSTANTS_COMMON_ORDER.contains(channel)) {
				
				//查询所有符合免费订单的人员
				  StuffListExample example = new StuffListExample(); 
				  example.setRegisterWhere(channel);
				List<DoctorListDto> list = stuffListDao.selectByQueryDocReq(example);
				toUserId = new String[list.size()];
				for (int i = 0; i < toUserId.length; i++) {
					DoctorListDto temp = list.get(i);
					toUserId[i]= String.valueOf(temp.getDocId());
					
					if (StringUtils.isNotEmpty(temp.getWxopenid())) {
						System.out.println(temp.getWxopenid());
						sendWX(sender, temp.getWxopenid(),mpService);
					}
				}
				
			}else{
				toUserId = new String[1];
				toUserId[0] = String.valueOf(order.getAccepterid());
			}
		
			OrdMsgMessage message = new OrdMsgMessage(Constant.CONSTANTS_RONGYUN_ORDER_2 , null,String.valueOf(order.getRegisterid()));
			logger.info("toUserIdSize##>" +toUserId.length);
			reslut = rongCloud.message.PublishSystem(
					String.valueOf(order.getUserid()),toUserId,message, 
					Constant.CONSTANTS_RONGYUN_ORDER_2, message.toString(), 0, 0);
			
		} catch (Exception e) {
			logger.error("refreshRongUserInfo", e);
		}
	
		return reslut;
	}
	
	/**
	 * 
	 * SkzI_qZ0snBg4bfuXgj5ff8RBYRhH9pfdA4cjtEHcyY
	 * 
	 * {{first.DATA}}
		用户姓名：{{keyword1.DATA}}
		消费金额：{{keyword2.DATA}}
		病情描述：{{keyword3.DATA}}
		{{remark.DATA}}
	 * 
	 * 您有一个新的即时咨询订单，请点击【问询】--【续诊】按钮
		用户姓名：王丽
		消费金额：100
		病情描述：腹痛不止，上吐下泻，连续高烧。
		感谢您的使用！
	 * 
	 */
	
	void sendWX(TemplateSender sender,String wxopenid,IService mpService){
		
        try {
        	sender.setTouser(wxopenid);
        	TemplateSenderResult senderResult=mpService.templateSend(sender);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	
	/**
	 * 微信推送消息
	 * @param order
	 * @return
	 */
	TemplateSender packageTemplate(RegisterOrder order){
		
		TemplateSender sender = new TemplateSender();
		
        sender.setTemplate_id("SkzI_qZ0snBg4bfuXgj5ff8RBYRhH9pfdA4cjtEHcyY");
        
        
        JSONObject keyword1 = new JSONObject();
        keyword1.put("color", "#173177");
        keyword1.put("value", order.getUserName());
        
        JSONObject first = new JSONObject();
        first.put("color", "#173177");
        first.put("value", "线上有新咨询，请及时回复");
        
        JSONObject keyword2 = new JSONObject();
        keyword2.put("color", "#173177");
        keyword2.put("value", "----");
        
        JSONObject remark = new JSONObject();
        remark.put("color", "#173177");
        remark.put("value", "感谢您的使用！");
        
        JSONObject keyword3 = new JSONObject();
        keyword3.put("color", "#173177");
        if (order.getRegistertypeid()==Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue()) {
        	keyword3.put("value", "挂号送药");
        }else{
        	keyword3.put("value", order.getRegisterDesc());
        }
        
        JSONObject map = new JSONObject();
        map.put("first", first);
        map.put("keyword1", keyword1);
        map.put("keyword2",keyword2);
        map.put("keyword3", keyword3);
        map.put("remark", remark);
        sender.setData(map);
		
		return sender;
		
	}
		
	
	//https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list?access_token=ACCESS_TOKEN
	
	
	/**
	 *自定义消息 ，订单处理 
	 *平台有新订单!
	 */
	@Override
	public CodeSuccessReslut PublishSystemOrderToDocMsgNoChannel(RegisterOrder order) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			String[] toUserId = new String[1];
			toUserId[0] = String.valueOf(order.getAccepterid());
			OrdMsgMessage message = new OrdMsgMessage(Constant.CONSTANTS_RONGYUN_ORDER_4 , null,String.valueOf(order.getRegisterid()));
			reslut = rongCloud.message.PublishSystem(
					String.valueOf(order.getUserid()),toUserId,message,
					Constant.CONSTANTS_RONGYUN_ORDER_2, message.toString(), 0, 0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	@Override
	public CodeSuccessReslut PublishSystemOrderToUserMsg(RegisterOrder order) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			//String orderId,String userId, String[] toUserId
			String[] toUserId = {String.valueOf(order.getUserid())};
			OrdMsgMessage message = new OrdMsgMessage(Constant.CONSTANTS_RONGYUN_ORDER_3 , null,String.valueOf(order.getRegisterid()));
			reslut = rongCloud.message.PublishSystem(
					String.valueOf(order.getAccepterid()),
					toUserId, 
					message, 
					Constant.CONSTANTS_RONGYUN_ORDER_3, message.toString(), 0, 0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	/**
	 * @return the stuffListDao
	 */
	public IStuffListDao getStuffListDao() {
		return stuffListDao;
	}

	/**
	 * @param stuffListDao the stuffListDao to set
	 */
	public void setStuffListDao(IStuffListDao stuffListDao) {
		this.stuffListDao = stuffListDao;
	}

	public IService getMpService() {
		return mpService;
	}

	public void setMpService(IService mpService) {
		this.mpService = mpService;
	}

	/**
	 * 发送推送消息
	 * */
	@Override
	public CodeSuccessReslut broadcastPush(PushMessage pushMessage) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			reslut=rongCloud.push.broadcastPush(pushMessage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	
	@Override
	public CodeSuccessReslut PublishSystemRecordToDocMsg(GoodsDataUser dataUser) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			String[] toUserId=null;
			
			String channel ="9";
			
			if (null!=dataUser.getAccepterId()&&dataUser.getAccepterId()!=0) {
				toUserId = new String[1];
				toUserId[0] = String.valueOf(dataUser.getAccepterId());
			}else{
				//查询所有符合免费订单的人员
				  StuffListExample example = new StuffListExample(); 
				  example.setRegisterWhere(channel);
				List<DoctorListDto> list = stuffListDao.selectByQueryDocReq(example);
				toUserId = new String[list.size()];
				for (int i = 0; i < toUserId.length; i++) {
					DoctorListDto temp = list.get(i);
					toUserId[i]= String.valueOf(temp.getDocId());
				}
			}
			AppTxtMsgMessage  message = new AppTxtMsgMessage(Constant.CONSTANTS_RONGYUN_H_ORDER_2, null);
			reslut = rongCloud.message.PublishSystem(
					String.valueOf(dataUser.getOwnerId()),toUserId,message, 
					Constant.CONSTANTS_RONGYUN_H_ORDER_2, message.toString(), 0, 0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	
	/**
	 * 单点一对一发送消息
	 */
	@Override
	public CodeSuccessReslut PublishSystemMsg(String fromUserId,String toUserId,String msg) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			String[] toUserIds = new String[1];
			toUserIds[0] = toUserId;
	
			AppTxtMsgMessage  message = new AppTxtMsgMessage(msg, null);
			reslut = rongCloud.message.PublishSystem(
					fromUserId,toUserIds,message, 
					msg, message.toString(), 0, 0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	
	
	/**
	 * 退出群组
	 * */
	@Override
	public CodeSuccessReslut quitGroup(String[] userIds, String groupId) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			rongCloud.group.quit(userIds, groupId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("userId="+JSONArray.toJSONString(userIds)+"-groupId="+groupId);
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	
	@Override
	public CodeSuccessReslut PublishSystemOrderToAssisMsg(String fromUserId, String toUserIds, String groupId) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			String[] toUserId=null;
			toUserId = new String[1];
			
			StuffDetailDto stuffDetail = stuffListDao. selectByStuffId(Long.parseLong(toUserIds));
			if(StringUtils.isNoneEmpty(stuffDetail.getStuffAlias())){
				
				String assistant = stuffDetail.getStuffAlias();
				
				toUserId[0]=assistant;
				
				OrdMsgMessage message = new OrdMsgMessage("平台有新订单!"+"医生:"+stuffDetail.getStuffName()+"电话:"+stuffDetail.getStuffNo(), null,groupId);
				logger.info("toUserIdSize##>" +toUserId.length);
				reslut = rongCloud.message.PublishSystem(
						fromUserId,toUserId,message, 
						"平台有新订单!"+"医生:"+stuffDetail.getStuffName()+"电话:"+stuffDetail.getStuffNo(), message.toString(), 0, 0);
				return reslut;
			}
		
			
		} catch (Exception e) {
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}

	@Override
	public CodeSuccessReslut PublishGroupMsg(RegisterOrder order) {
		// TODO Auto-generated method stub
		CodeSuccessReslut reslut=null;
		RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
		try {
			
			if (order.getRunstatusid().intValue()!=2) {
				return null;
			}
			
			String[] messagePublishGroupToGroupId = {String.valueOf(order.getRegisterid())};
			
			int channel = Integer.valueOf(order.getRegisterguideid());
			String messageStr = "";
			System.out.println(channel);
			if (channel==Constant.CONSTANTS_ORDER_CHANNEL_ID_1.intValue()||channel==Constant.CONSTANTS_ORDER_CHANNEL_ID_4.intValue()||channel==Constant.CONSTANTS_ORDER_CHANNEL_ID_8.intValue()) {
				messageStr=Constant.CONSTANTS_RECEIVED_AUTO_REPLY_CS;
			}else{
				messageStr=Constant.CONSTANTS_RECEIVED_AUTO_REPLY_DOC;
			}
			
			TxtMessage messagePublishGroupTxtMessage = new TxtMessage(messageStr, null);
			CodeSuccessReslut messagePublishGroupResult = rongCloud.message.publishGroup("69", messagePublishGroupToGroupId, messagePublishGroupTxtMessage, 
					messageStr, messagePublishGroupTxtMessage.toString(), 1, 1);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("refreshRongUserInfo", e);
		}
		return reslut;
	}
	
	
}
